﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Linq;
using Flower.Directory.Host.Default;
using NUnit.Framework;
using System.Security.Principal;
using Flower.Testing;

namespace Flower.Security.Tests
{
    [TestFixture]
    public class AuthorizationProviderTest
    {
        private class TestIdentity : IIdentity
        {
            private readonly string _name;

            public TestIdentity(string name)
            {
                _name = name;
            }

            public string AuthenticationType
            {
                get { return null; }
            }

            public bool IsAuthenticated
            {
                get { return true; }
            }

            public string Name
            {
                get { return _name; }
            }
        }

        [Test]
        public void Authorize()
        {
            var scriptEnginePool = new ScriptEnginePool(1);
            var proxyProvider = new DirectoryProxyProvider();
            var dir = new MemoryDirectory.Directory(scriptEnginePool, proxyProvider);

            new DirectoryBuilder(dir)
                .Root("/Roles/Application")
                    .Role("App1", new [] { "user1", "user2", "user3" })
                        .Role("SubApp1", new[] { "user1", "user4" }).End()
                    .End()
                    .Role("App2", new[] { "user1", "user2" }).End()
                .End();

            using (var authorizationProvider = new AuthorizationProvider(TimeSpan.FromHours(1)) { Directory = dir })
            {
                string[] user1Roles = authorizationProvider.GetUserRoles(new TestIdentity("user1"));
                
                Assert.AreEqual(2, user1Roles.Length);
                Assert.IsTrue(user1Roles.Contains("Application/App1") && user1Roles.Contains("Application/App2"));

                string[] user4Roles = authorizationProvider.GetUserRoles(new TestIdentity("user4"));

                Assert.AreEqual(1, user4Roles.Length);
                Assert.IsTrue(user4Roles.Contains("Application/App1/SubApp1"));
            }
        }
    }
}
